﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Globalization;
using System.Reflection;

namespace WpfAsteriskCTI
{
    public class cIniReader
    {
        private string _filePath;

        public cIniReader(string filePath)
        {
            _filePath = filePath;
        }


        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string Key,
                                                          string value, StringBuilder result, int size, string filePath);

        public string ReadString(string section, string key, string defaultValue = null)
        {
            var temp = new StringBuilder(500);
            GetPrivateProfileString(section, key, "", temp, 500, _filePath);
            var strValue = temp.ToString();
            return string.IsNullOrEmpty(strValue) && defaultValue != null ? defaultValue : strValue;
        }

        public int ReadInt(string section, string key, NumberStyles style, int defaultValue = 0)
        {
            int i;
            return int.TryParse(ReadString(section, key).Replace("0x", ""), style, null, out i) ? i : defaultValue;
        }

        public float ReadFloat(string section, string key, float defaultValue = 0)
        {
            float f;
            return float.TryParse(ReadString(section, key), out f) ? f : defaultValue;
        }

        public double ReadDouble(string section, string key, double defaultValue = 0)
        {
            double d;
            return double.TryParse(ReadString(section, key), out d) ? d : defaultValue;
        }

        public decimal ReadDecimal(string section, string key, decimal defaultValue = 0)
        {
            decimal d;
            return decimal.TryParse(ReadString(section, key), out d) ? d : defaultValue;
        }

        public bool ReadBoolean(string section, string key, bool defaultValue = false)
        {
            bool b;
            return bool.TryParse(ReadString(section, key), out b) ? b : defaultValue;
        }
    }
}
